<template>
  <div>

    <el-tabs v-model="editableTabsValue" :closable="editableTabs.length > 1" @tab-remove="removeTab" @tab-click="handleClick($event)"
             class="tabs-class">
      <el-tab-pane
        v-for="(item, index) in editableTabs"
        :key="index"
        :label="item.name"
        :name="item.path"
      >
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
  import {mapState} from 'vuex'

  export default {
    data() {
      return {
        editableTabsValue: '',
        editableTabs: [],
      }
    },
    computed: {
      ...mapState({
        openedTab: state => state.tabs.openedTab,
        activeTab: state => state.tabs.activeTab
      })
    },
    methods: {
      removeTab(path) {
        let targetPath = path;
        let tabs = this.editableTabs;
        let activePath = this.editableTabsValue;
        if (activePath === targetPath) {
          tabs.forEach((tab, index) => {
            if (tab.path === targetPath) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activePath = nextTab.path
              }
            }
          });
        }
        this.$store.commit('deductTab', path)
        this.editableTabsValue = activePath
        this.editableTabs = tabs.filter(tab => tab.path !== targetPath)
        this.$router.push(activePath)
      },
      handleClick(event) {
        this.$store.commit('changeTab', event.name)
        this.$router.push(event.name)
      }
    },
    watch: {
      openedTab(val) {
        if (val.length > this.editableTabs.length) {
          // 添加了新的tab页
          // 导致$store.state中的openedTab长度大于标签页中的openedTab长度
          // 因此需要新增标签页
          let newTab = val[val.length - 1] // 新增的肯定在数组最后一个
          ++this.tabIndex
          this.editableTabs.push(newTab)
          this.editableTabsValue = newTab.path

          // this.openedTab.push(newTab)
        }
      },
      activeTab(val) {
        // 监听activetab以实现点击左侧栏时激活已存在的标签
        if (val !== this.editableTabsValue) {
          this.editableTabsValue = val
        }
      }
    },
    mounted() {
      this.editableTabs = JSON.parse(sessionStorage.getItem('openedTab'))
      this.editableTabsValue = sessionStorage.getItem('activeTab')
      let openedTab = this.editableTabs
      let activeTab = this.editableTabsValue
      if (openedTab !== null) {
        this.$store.commit('setOpenedTab', {openedTab, activeTab})
      }
    }
  }
</script>
<style lang="scss">
  .tabs-class .el-tabs__nav-scroll {
    margin-left: 1.2rem;
  }
</style>
